package com.hejjon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hejjon.core.domain.entity.FeatureCategory;
import com.hejjon.core.domain.entity.FeatureField;
import com.hejjon.core.domain.entity.FeaturePublishCategory;
import com.hejjon.core.enumer.DeleteFlagEnum;
import com.hejjon.core.exception.BusinessException;
import com.hejjon.core.utils.StrUtil;
import com.hejjon.core.utils.TreeBuilder;
import com.hejjon.domain.request.FeaturePublishCategoryRequest;
import com.hejjon.domain.vo.FeaturePublishCategoryVO;
import com.hejjon.mapper.FeaturePublishCategoryMapper;
import com.hejjon.service.IFeaturePublishCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;


@Service
public class FeaturePublishCategoryServiceImpl extends ServiceImpl<FeaturePublishCategoryMapper, FeaturePublishCategory> implements IFeaturePublishCategoryService {


    @Resource
    private FeaturePublishCategoryMapper featurePublishCategoryMapper;

    @Override
    public boolean add(FeaturePublishCategoryRequest request) {

        String parentId = request.getParentId();
        if (StringUtils.isEmpty(parentId)) {
            parentId = "-1";
        }
        String uuid = StrUtil.getUUID();
        FeaturePublishCategory entity = new FeaturePublishCategory();
        entity.setId(uuid);
        entity.setName(request.getName());
        entity.setParentId(parentId);
        entity.setCreateTime(LocalDateTime.now());
        entity.setCreateBy("admin");
        entity.setDeleteFlag(DeleteFlagEnum.NO.getCode());
        return  featurePublishCategoryMapper.insert(entity) > 0;
    }


    @Override
    public boolean removeById(String id) {

        Integer childsCount = featurePublishCategoryMapper.existChildsById(id);
        if (childsCount != null) {
            throw new BusinessException("该节点存在子节点不可删除");
        }
        return baseMapper.update(new LambdaUpdateWrapper<FeaturePublishCategory>()
                .eq(FeaturePublishCategory::getId,id)
                .eq(FeaturePublishCategory::getDeleteFlag,DeleteFlagEnum.NO.getCode())
                .set(FeaturePublishCategory::getDeleteFlag,DeleteFlagEnum.YES.getCode())
                .set(FeaturePublishCategory::getUpdateBy,"admin").set(FeaturePublishCategory::getUpdateTime,LocalDateTime.now())) > 0;
    }

    @Override
    public List<FeaturePublishCategoryVO> listCategoryTree(FeaturePublishCategoryRequest request) {

        List<FeaturePublishCategoryVO> voList = baseMapper.selectAllBy(request);
        TreeBuilder<FeaturePublishCategoryVO, String> builder = new TreeBuilder<>();
        return builder.buildTree(voList);
    }

}
